const Joi = require('joi');

async function codeValidate(params) {
  const schema = Joi.object({
    visitor: Joi.string(),
  });

  try {
    const value = await schema.validateAsync(params);
    return value;
  } catch (error) {
    throw new Error(error.message ?? '参数错误');
  }
}

async function loginValidate(params) {

  const schema = Joi.object({
    login_name: Joi.string()
      .required()
      .pattern(/^[^\s]+$/)
      .messages({
        'string.pattern': '登录名不能包含空格以及特殊字符',
        'string.empty': '登录名不能为空',
        'any.required': '登录名是必填项',
      }),

    password: Joi.string()
      .min(8)
      .required()
      .pattern(/^(?=.*[A-Z])(?=.*[!@#$%^&*]).+$/)
      .messages({
        'string.pattern': '密码中必须至少包含一个大写字母一个小写字母一个特殊字符',
        'string.empty': '密码不能为空',
        'string.min': '密码不能少于8位',
        'any.required': '密码是必填项',
      }),

    code: Joi.string().required().messages({
      'string.empty': '验证码不能为空',
      'any.required': '验证码是必填项',
    }),

    visitor: Joi.string().required().messages({
      'string.empty': '游客不能为空',
      'any.required': '游客是必填项',
    }),
  });

  try {
    const value = await schema.validateAsync(params);
    return value;
  } catch (error) {
    throw new Error(error.message ?? '参数错误');
  }
}

async function checkoutValidate(params) {
  const schema = Joi.object({
    key: Joi.string().empty().required()
      .messages({
        'string.empty': 'key不能为空',
        'any.required': 'key是必填项',
      }),
    role_id: Joi.string().empty().required()
      .messages({
        'string.empty': 'role_id不能为空',
        'any.required': 'role_id是必填项',
      }),
  });

  try {
    const value = await schema.validateAsync(params);
    return value;
  } catch (error) {
    throw new Error(error.message ?? '参数错误');
  }
}

module.exports = {
  codeValidate,
  loginValidate,
  checkoutValidate,
};
